﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OperaHouse.Business.Users;
using OperaHouse.Web.Areas.Admin.Models;
using OperaHouse.Common;
using System.Web.Security;

namespace OperaHouse.Web.Areas.Admin.Controllers
{
    [Authorize]
    public class UserController : BaseController
    {
        #region Fields
        private readonly IUserService _userService;
        #endregion

        #region Ctor
        public UserController(IUserService userService)
        {
            this._userService = userService;
        }
        #endregion

        #region Utilities
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        #endregion

        [AllowAnonymous]
        public ActionResult Logon(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Logon(LogonModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                string password = CommonHelper.Md5EncryptPassword(model.Password);

                var user = _userService.GetUserLogin(model.UserName.Trim(), password);
                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(user.Id.ToString(), true);
                    FormsAuthentication.RedirectFromLoginPage(user.Id.ToString(), model.RememberMe);

                    return RedirectToLocal(returnUrl);
                }
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

    }
}
